<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- <el-button size="small" type="primary" @click="handleDelete()" class="myBtnMoreDel" icon="el-icon-delete"
            v-if="isMoreDel">
            批量删除
        </el-button> -->
    <el-button size="small"
               type="default"
               @click="handleAdd"
               icon="el-icon-plus"
               class="myBtnAdd">
      添 加
    </el-button>
    <el-table :data="tableData"
              style="margin-top:30px"
              row-key="id"
              :tree-props="{children: 'children'}"
              @selection-change="handleSelectionChange"
              reserve-selection="true">
      <!-- <el-table-column type="selection" width="50" fixed="left"></el-table-column> -->
      <el-table-column prop="name"
                       label="角色名称"></el-table-column>
      <el-table-column prop="tips"
                       label="备注"></el-table-column>
      <el-table-column label="操作"
                       width="250"
                       fixed="right">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="default"
                     @click="handleEdit(scope.$index, scope.row)">
            编辑</el-button>
          <el-button size="mini"
                     type="primary"
                     @click="handleDelete(scope.$index, scope.row)">
            删除</el-button>
          <el-button size="mini"
                     type="default"
                     @click="handleSetting(scope.$index, scope.row)">
            权限配置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="formInline.page"
                   :page-size="formInline.limit"
                   :hide-on-single-page="true"
                   layout="total, prev, pager, next"
                   :total="total">
    </el-pagination> -->
    <!-- 添加-编辑 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="centerDialogVisible"
               :before-close="handleClose"
               width="40%"
               center
               custom-class="center_dislog">
      <el-form ref="editForm"
               :model="editForm"
               label-width="100px">
        <!-- 角色名称-->
        <el-form-item label="角色名称"
                      prop="RoleName">
          <el-input v-model="editForm.RoleName"></el-input>
        </el-form-item>
        <!-- 上级 -->
        <el-form-item label="上级角色"
                      prop="carrierAccount">
          <el-tree :data="tableData"
                   :props="roleDefaultProps"
                   @check-change="handleNodeRoleChange"
                   show-checkbox
                   ref="role_tree"
                   node-key="id"
                   class="myDialogTree">
          </el-tree>
          <!-- <el-select v-model="editForm.pid" placeholder="请选择" filterable>
                        <el-option v-for="(item, index) in tableData" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select> -->
        </el-form-item>
        <!-- 排序 -->
        <el-form-item label="排序"
                      prop="num">
          <el-input v-model="editForm.SortNum"></el-input>
        </el-form-item>
        <!-- 备柱 -->
        <!-- <el-form-item label="备注"
                      prop="tips">
          <el-input v-model="editForm.tips"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary"
                   :disabled="addDisabled"
                   @click="updateSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="权限分配"
               :visible.sync="centerDialogSetting"
               width="40%"
               center
               :before-close="beforeClose"
               custom-class="center_dislog">
      <el-form ref="settingForm"
               :model="settingForm"
               label-width="80px">
        <!-- 权限 -->
        <el-form-item label="权限设置">
          <el-tree style="max-height:500px;overflow-y: auto;"
                   :data="muneData"
                   show-checkbox
                   node-key="id"
                   :default-expanded-keys="menuDefaule"
                   :default-checked-keys="menuDefaule"
                   :props="defaultProps"
                   ref="menu_tree"
                   :check-strictly="checkStrictly"
                   class="myDialogTree">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary"
                   :disabled="setDisabled"
                   @click="settingSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
import {
  mapState
} from 'vuex'
import {
  roleList,
  roleAdd,
  roleEdit,
  roleDelete,
  roleResource,
  getMenuDate,
  menuList
} from '../../api.js'
export default {
  name: "systemRole",
  data () {
    return {
      isAdd: true,
      dialogTitle: '',
      isMoreDel: false,
      multipleSelection: [],
      centerDialogVisible: false,
      centerDialogSetting: false,
      breadcrumbName: '',
      breadcrumbPath: '',
      breadcrumbNameP: '',
      checkStrictly: true,
      tableData: [],
      editForm: {
        RoleId: '',
        SortNum: '',
        Pid: '',
        RoleName:''
        // tips: '',
      },
      settingForm: {
        RoleId:'',
        ResourceIds:''
      },
      //分页
      total: 0,
      // 树形数据
      muneData: [],
      menuDefaule: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formInline: {
        page: 1,
        limit: 10,
      },
      roleDefaultProps: {
        children: 'children',
        label: 'name'
      },
      addDisabled: false,
      setDisabled: false,
    }
  },
  mounted () {
    this.breadcrumbName = this.$route.query.breadcrumbName
    this.breadcrumbPath = this.$route.query.breadcrumbPath
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP
    this.getTableDate();
    this.getMenuDate();
  },
  methods: {
    //获取表格数据
    getTableDate () {
      var _this = this;
       roleList().then(res => {
          if (res.ErrorCode == 0) {
              _this.tableData = res.Data
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
    },
    getMenuDate () {
      var _this = this;
      menuList().then(res => {
        if (res.ErrorCode == 0) {
            _this.muneData = res.Data
        } else {
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    //表格查询
    onSearch () {
      this.getTableDate();
    },
    //添加
    handleAdd () {
      this.isAdd = true;
      this.getTableDate();
      this.dialogTitle = '添 加';
      this.centerDialogVisible = true
      for (var k in this.editForm) {
        this.editForm[k] = ''
      }
    },
    //表格的操作
    //编辑
    handleEdit (index, row) {
      this.isAdd = false;
      this.dialogTitle = '编 辑';
      var _this = this;
      this.centerDialogVisible = true
      this.editForm.RoleId = row.id
      this.editForm.SortNum = row.num
      this.editForm.Pid = row.pid
      this.editForm.RoleName = row.name
      // this.editForm.tips = row.tips
      setTimeout(function () {
        _this.$refs.role_tree.setCheckedKeys([row.pid])
      }, 50)
    },
    //删除
    handleDelete (index, row) {
      var _this = this
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
          roleDelete({id: row.id}).then(res => {
            if (res.ErrorCode == 0) {
              _this.$message.success("删除成功");
              _this.getTableDate();
            } else {
              this.$message.error(res.message);
            }
          })
      }).catch(() => {

      });
    },
    //选中表格数据
    handleSelectionChange (val) {
      if (val.length == 0) {
        this.isMoreDel = false
      } else {
        this.isMoreDel = true
      }
      this.multipleSelection = val
    },
    //提交
    updateSubmit () {
      this.addDisabled = true
      var _this = this;
      var dataObj ={}
      if (this.isAdd) {
          dataObj["name"] = _this.editForm.RoleName
          dataObj["pid"] = _this.editForm.Pid
          dataObj["num"] = _this.editForm.SortNum
          roleAdd(dataObj).then(res => {
            if (res.ErrorCode == 0) {
              _this.addDisabled = false;
                _this.centerDialogVisible = false;
                _this.$message.success("添加成功");
                _this.$refs.role_tree.setCheckedKeys([])
                _this.getTableDate();
            } else {
              _this.addDisabled = false;
              this.$message.error(res.ErrorMsg);
            }
          })
      }else{
          dataObj["id"] = _this.editForm.RoleId
          dataObj["name"] = _this.editForm.RoleName
          dataObj["pid"] = _this.editForm.Pid
          dataObj["num"] = _this.editForm.SortNum
          roleEdit(dataObj).then(res => {
          if (res.ErrorCode == 0) {
            _this.addDisabled = false;
              _this.centerDialogVisible = false;
              _this.$message.success("编辑成功");
              _this.$refs.role_tree.setCheckedKeys([])
              _this.getTableDate();
          } else {
            _this.addDisabled = false;
            this.$message.error(res.ErrorMsg);
          }
        })
      }
    },
    handleSetting (index, row) {
      var _this = this;
      _this.settingForm.RoleId = row.id
      /** 将树的父级与子级关联移除 */
        _this.centerDialogSetting = true;
        _this.$nextTick(() => {
          _this.$refs.menu_tree.setCheckedKeys(row.resourceIdArr)
        })
    },
    settingSubmit () {
      this.setDisabled = true;
      var _this = this;
      var p_codes = []
      _this.$refs.menu_tree.getCheckedNodes(false, true).forEach(function (item) {
        p_codes.push(item.id)
      })
      roleResource({
        id:_this.settingForm.RoleId,
        ids:p_codes.join(',')
      }).then(res => {
        if (res.ErrorCode == 0) {
            _this.$message.success("分配成功");
            _this.setDisabled = false;
            _this.centerDialogSetting = false;
            _this.$refs.menu_tree.setCheckedKeys([])
            _this.getTableDate();
        } else {
          _this.setDisabled = false;
          this.$message.error(res.message);
        }
      })
    },
    handleNodeRoleChange (node, checked, indeterminate) {
      if (checked) {
        this.$refs.role_tree.setCheckedKeys([node.id])
        this.editForm.Pid = node.id
      }
    },
    beforeClose () {
      this.centerDialogSetting = false
      this.$refs.menu_tree.setCheckedKeys([])
    },
    handleClose () {
      this.centerDialogVisible = false 
      this.$refs.role_tree.setCheckedKeys([])
    }
  },
  computed: {
    ...mapState({
      access_token: state => state.access_token,
      baseUrl: state => state.baseUrl,
    }),
  },
}
</script>

<style scoped>
.myBtnAdd {
  position: absolute;
  right: 25px;
  top: 96px;
}

.myBtnMoreDel {
  position: absolute;
  right: 100px;
  top: 96px;
}
</style>